package com.yunxiang.base;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;

public class BaseController extends Controller{
	/**
	 * 将record 转换为JSONObject
	 * 
	 * @return
	 */
	public JSONObject recordToJson(Record record) {
		JSONObject result = new JSONObject();
		try {
			if (record != null) {
				return JSONObject.fromObject(record.toJson().replaceAll(":null", ":\"\""));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 将record 转换为JSONObject
	 * 
	 * @return
	 */
	public JSONArray recordListToJsonArray(List<Record> records) {
		JSONArray result = new JSONArray();
		if (records != null && records.size() > 0) {
			for (Record record : records) {
				result.add(JSONObject.fromObject(record.toJson().replaceAll(":null", ":\"\"")));
			}
		}
		return result;
	}
	/**
	 * json格式化输出
	 */
	public void renderTempletJson(boolean flag, String msg, Object data) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("flag", flag);
		jsonObject.put("msg", msg);
		jsonObject.put("data", data);
		super.renderJson(jsonObject.toString());
	}
}
